package db_guess

import (
	"errors"
	"fmt"
	global2 "longmen/server/config/global"
	utils2 "longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_guess"
	"reflect"

	"gorm.io/gorm"
	"longmen/server/pkg/common/api_models"
)

/*
*
@Create 2022 July19 Enzo
看一个主播是不是有发起竞猜的权限
*/
func CheckAnchorCanHostGuess(anchorId int) (bool, error) {
	anchor, err := mysql.GetUserParam(map[string]interface{}{"id": anchorId, "is_guess_host": 1, "is_anchor": 1})
	if err == gorm.ErrRecordNotFound {
		err = nil
	}
	if err != nil {
		return false, err
	}
	if anchor == nil || anchor.Id == 0 {
		return false, nil
	}
	return true, nil
}

func GuessInsertAny(o interface{}, comment string) (int, error) {
	err := global2.Guess().Create(o).Error
	if err != nil {
		return 0, fmt.Errorf("%s%s", err)
	}
	if o == nil {
		return 0, errors.New("guess增加记录错误")
	}

	vLog := reflect.ValueOf(o).Elem()
	id := vLog.FieldByName("Id")

	if id.Kind() == 0 {
		return 0, errors.New("guess增加记录错误")
	}
	return int(id.Int()), nil
}

func GuessInsertAnyByTx(session *gorm.DB, o interface{}, comment string) (int, error) {
	err := session.Create(o).Error
	if err != nil {
		return 0, err
	}
	requestValue := reflect.ValueOf(o)
	id := requestValue.FieldByName("Id")
	if id.Kind() == 0 {
		return 0, errors.New("增加记录错误")
	}
	return int(id.Int()), nil
}

func GetGuessAnyParam(o interface{}, param map[string]interface{}, bLast bool, comment string) error {
	var err error
	table := mysql.GetGuessTable(&o)
	mysql.Condition(table, param, "", "", 0, 0)
	if bLast {
		err = table.Order("id desc").Limit(1).Find(o).Error
	} else {
		err = table.Find(o).Error
	}
	if err == gorm.ErrRecordNotFound {
		err = nil
	}
	if err != nil {
		return err
	}
	return nil
}

// seed:传入要查的struct类型的指针
func GetGuessAnyListParam(seed interface{}, oList interface{}, param map[string]interface{}, comment string,
	order string, page, size int) error {
	if len(order) == 0 {
		order = "create_time desc"
	}
	err := mysql.Condition(mysql.GetGuessTable(seed), param, "", order, page, size).
		Find(oList).
		Error
	if err == gorm.ErrRecordNotFound {
		err = nil
	}
	return err
}

// seed:传入要查的struct类型的指针
func CountGuessAnyParam(seed interface{}, n *int64, param map[string]interface{}, comment string,
	order string, page, size int) error {
	err := mysql.Condition(mysql.GetGuessTable(seed), param, "", order, page, size).
		Count(n).
		Error
	if err == gorm.ErrRecordNotFound {
		err = nil
	}
	return err
}

/*
去库里更新任何东西，必需带 Id
session为空时会当场提交到guess库
o := &models.any{}
*/
func UpdateGuessAnyWithId(session *gorm.DB, columns []string, o interface{}, comment string) error {
	bCommitHere := false
	vLog := reflect.ValueOf(o).Elem()
	oId := vLog.FieldByName("Id")
	if oId.Kind() == 0 {
		return errors.New("69Invalid Id")
	}
	id := int(oId.Int())
	if session == nil {
		bCommitHere = true
		session = global2.Guess().Begin()
	}
	err := session.Where("id = ?", id).Select(columns).Updates(o).Error
	if err != nil {
		session.Rollback()
		return err
	}
	if bCommitHere {
		err = session.Commit().Error
	}
	return err
}

// 从库里面取订单，重新计算取投注列表，人数列表，赔率列表
// todo加缓存
func GetGuessOrdersSumFromDB(g_id int, gInfo *api_models.GuessInfo) {
	gInfo.AmountList = make([]int, gInfo.ItemNum, gInfo.ItemNum)
	gInfo.OddsList = make([]int, gInfo.ItemNum, gInfo.ItemNum)
	gInfo.PeopleNumList = make([]int, gInfo.ItemNum, gInfo.ItemNum)

	oList := make([]*models_guess.GuessOrder, 0)
	err := mysql.GetXAnyListParam(&models_guess.GuessOrder{}, &oList,
		map[string]interface{}{"guess_id": g_id}, "getGuessOrder", "", 0, 0)
	mTmp := make(map[int]struct{})     //传说中的空结构体
	if err != nil || len(oList) == 0 { //订单列表
		//		global.Log.Info("6AddGuessUserInfo9:用户没有本场记录")
	} else {
		for _, v := range oList {
			gInfo.AmountList[v.GuessItem-1] += v.Amount
			if _, ok := mTmp[v.Uid]; !ok { //查重复
				mTmp[v.Uid] = struct{}{}
				gInfo.PeopleNumList[v.GuessItem-1]++
			}
		}
		utils2.CalcOddsListFromAmountList(&gInfo.AmountList, &gInfo.OddsList)
	}
}
